//
//  SXWYNewsMainViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXWYNewsMainViewController.h"
#import "SXWYNewsCommonCell.h"
#import "SXWYNewsOneImageCell.h"
#import "SXWYNewsThreeImageCell.h"
#import "SXRequestManager.h"
#import "SXDataBaseManager.h"
#import "SXWYDetailImageViewController.h"
#import "SXWYDetailArticleViewController.h"
#import "PKCarouselFigure.h"
#import "SXWYFigureMainModel.h"
@interface SXWYNewsMainViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) PKCarouselFigure *headerView;
@property(nonatomic, strong) NSMutableArray *headerImgArray; // 图片url
@property (nonatomic, strong) NSMutableArray *headerDetailArray; // 图片进入详情
@end

@implementation SXWYNewsMainViewController

- (void)dealloc
{
    if (_headerView) {
        [_headerView removeTime];
    }
}

- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 143) style:UITableViewStylePlain];
        _mainTableView.dataSource = self;
        _mainTableView.delegate = self;
        [_mainTableView registerClass:[SXWYNewsOneImageCell class] forCellReuseIdentifier:@"SXWYNewsOneImageCell"];
        [_mainTableView registerClass:[SXWYNewsCommonCell class] forCellReuseIdentifier:@"SXWYNewsCommonCell"];
        [_mainTableView registerClass:[SXWYNewsThreeImageCell class] forCellReuseIdentifier:@"SXWYNewsThreeImageCell"];
        
    }
    return _mainTableView;
}
// 加载轮播图
- (PKCarouselFigure *)headerView
{
    if (_headerView == nil) {
        _headerView = [[PKCarouselFigure alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 26 * kScreenWidth / 45)];
        __weak SXWYNewsMainViewController *test = self;
        _headerView.tapBlock = ^(NSInteger tapNum){
            SXWYFigureMainModel *model = test.headerDetailArray[tapNum];
            if ([model.tag isEqualToString:@"photoset"]) {
                SXWYDetailImageViewController *detailImageVC = [[SXWYDetailImageViewController alloc] init];
                detailImageVC.photoStr = [model.url substringFromIndex:4];
                [test.rootRightVC.navigationController pushViewController:detailImageVC animated:YES];
            }else{
                SXWYDetailArticleViewController *detailArticleVC = [[SXWYDetailArticleViewController alloc] init];
                detailArticleVC.docidStr = model.url;
                [test.rootRightVC.navigationController pushViewController:detailArticleVC animated:YES];
            }
        };
        self.mainTableView.tableHeaderView = _headerView;
    }
    return _headerView;
}
- (NSMutableArray *)headerImgArray
{
    if (!_headerImgArray) {
        _headerImgArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _headerImgArray;
}

- (NSMutableArray *)headerDetailArray
{
    if (!_headerDetailArray) {
        _headerDetailArray = [NSMutableArray array];
    }
    return _headerDetailArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _start = 0;
    _limit = 20;
    [SXDataBaseManager DBManage:nil dataName:_URLString manageType:dataBaseManageTypeQueryData getDataFromDict:^(NSData *data) {
        if (data) {
            [self analyzeData:data];
        }
    }];
    [self requestData];
    // Do any additional setup after loading the view.
}
// 网络请求
- (void)requestData
{
    NSString *URLStr = [kWYNewsMainListURLString stringByAppendingString:_URLString];
    URLStr = [URLStr stringByAppendingString:[NSString stringWithFormat:@"%ld-%ld.html", _start, _limit]];
    [SXRequestManager requestWithType:GET urlString:URLStr parDic:nil finish:^(NSData *data) {
        if (_start == 0) {
            [SXDataBaseManager DBManage:data dataName:_URLString manageType:dataBaseManageTypeStoreData getDataFromDict:nil];
        }
        [self analyzeData:data];
        [self removeLoadingView];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [self removeLoadingView];
    }];
}
// 解析数据
- (void)analyzeData:(NSData *)data
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if (_start == 0) {
        [self.dataSourceArray removeAllObjects];
    }
    NSString *dataString;
    if (_URLString.length > 21) {
        dataString = [_URLString substringWithRange:NSMakeRange(9, 14)];
    }
    else
    {
        dataString = [_URLString substringWithRange:NSMakeRange(5, 14)];
    }
    for (NSDictionary *headLineDic in dic[dataString]) {
        SXWYNewsMainModel *headLineModel = [[SXWYNewsMainModel alloc] init];
        
        [headLineModel setValuesForKeysWithDictionary:headLineDic];
        if (!([headLineModel.TAGS isEqualToString:@"正在直播"] || [headLineModel.TAGS isEqualToString:@"视频"] || [headLineModel.skipType isEqualToString:@"special"])) {
            [self.dataSourceArray addObject:headLineModel];
        }
    }
    if (_start == 0 && [dataString isEqualToString:@"T1348647853363"]) {
        NSMutableArray *imgArray = [NSMutableArray array];
        NSMutableArray *urlArray = [NSMutableArray array];
        for (NSDictionary *imgDic in dic[dataString][0][@"ads"]) {
            [imgArray addObject:imgDic[@"imgsrc"]];
            SXWYFigureMainModel *model = [[SXWYFigureMainModel alloc] init];
            [model setValuesForKeysWithDictionary:imgDic];
            [urlArray addObject:model];
        }
        self.headerImgArray = imgArray;
        self.headerDetailArray = urlArray;
        
        self.headerView.figureURLArray = self.headerImgArray;
    }

    [self.mainTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}
// cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXWYNewsMainModel *model = _dataSourceArray[indexPath.row];
    
    if (model.imgType == 1) {
        SXWYNewsOneImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SXWYNewsOneImageCell" forIndexPath:indexPath];
        cell.configureModel = model;
        return cell;
    }
   else if (model.imageArray.count > 0)
    {
        SXWYNewsThreeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SXWYNewsThreeImageCell" forIndexPath:indexPath];
        cell.configureModel = model;
        return cell;
    }
    else
    {
        SXWYNewsCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SXWYNewsCommonCell" forIndexPath:indexPath];
        cell.configureModel = model;
        return cell;
    }
}
// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXWYNewsMainModel *model = self.dataSourceArray[indexPath.row];
    if (model.imgType == 1) {
        return 80 + (kScreenWidth - 20) / 3;
    }
    else if (model.imageArray.count > 0)
    {
        return (kScreenWidth - 30) / 4 + 50;
    }
    else
    {
        return 20 * (kScreenWidth - 30) / 81 + 140 / 27;
    }
}
// cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXWYNewsMainModel *model = self.dataSourceArray[indexPath.row];
    if ([model.skipType isEqualToString:@"photoset"]) {
        SXWYDetailImageViewController *detailImageVC = [[SXWYDetailImageViewController alloc] init];
        detailImageVC.photoStr = [model.photosetID substringFromIndex:4];
        [self.rootRightVC.navigationController pushViewController:detailImageVC animated:YES];
    }else{
        SXWYDetailArticleViewController *detailArticleVC = [[SXWYDetailArticleViewController alloc] init];
        detailArticleVC.docidStr = model.docid;
        detailArticleVC.shareStr = model.url;
        [self.rootRightVC.navigationController pushViewController:detailArticleVC animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
